import { ActionType, LightFilter, ProFormDatePicker, ProFormInstance } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Button, Modal } from 'antd';
import React, { useContext } from 'react';
import { useRef, useState } from 'react';
import PropTypes from 'prop-types';
import { PlusOutlined } from '@ant-design/icons';
import { initConfig } from './config';
import ProFormDynamicSettings from '../ProFormDynamicSettings'; // 带配置的ProForm
import ProFormDynamic from './subComps/ProFormDynamic'; // 不带配置的ProForm
import {
  ApiInfo,
  ApiType,
  EventInfo,
  EventTableType,
  FormType,
  ModalInfo,
  Modals,
  ModalsInfoConfig,
  ModalType,
  ProTableContexteValue,
  ProTableMenuInfo,
  ProTableSearch,
  TablePagination,
  TableRecord,
} from './utils/types';
import { dataSource } from './utils/dataSource';
import { ProTableContext } from '../Context/ProTableContext';
import dayjs from 'dayjs';

const ProTableDynamic = (props: any) => {
  const proTableFormRef = useRef<ProFormInstance>();
  const proTableActionRef = useRef<ActionType>();
  let [config, setConfig] = new Array();

  const [currentTableRecord, setCurrentTableRecord] = useState<TableRecord>({ reactNode: undefined, record: {}, index: 1 });
  const [modalsInfoConfig, setModalsInfoConfig] = useState<ModalsInfoConfig>(
    /// 开始删除
    props.dynamic
      ? {
          modals: {
            setting: {
              title: '表单配置',
              open: false,
              width: 1600,
              reactNode: <>{Date.now()}</>,
            },
          } as Modals,
        }
      : ///结束删除
        {
          modals: {
            add: {
              title: '新增',
              open: false,
              reactNode: <ProFormDynamic formType="add" config={config} isTable={true} currentTableRecord={currentTableRecord} />,
            },
            detail: {
              title: '新增',
              open: false,
              reactNode: <ProFormDynamic formType="detail" config={config} isTable={true} currentTableRecord={currentTableRecord} />,
            },
            edit: {
              title: '新增',
              open: false,
              reactNode: <ProFormDynamic formType="edit" config={config} isTable={true} currentTableRecord={currentTableRecord} />,
            },
          } as Modals,
        },
  );
  const toggleModalOpen = (modalType: ModalType) => {
    const myModalType = modalType;
    modalsInfoConfig.modals[myModalType].open = !modalsInfoConfig.modals[myModalType].open;
    setModalsInfoConfig({ ...modalsInfoConfig });
  };
  // 操作事件
  const onSubEvent = async (eventInfo?: EventInfo) => {
    switch (eventInfo?.type) {
      case 'detail': {
        toggleModalOpen('detail');
        setCurrentTableRecord(eventInfo?.tableRecord as TableRecord);
        break;
      }
      case 'edit': {
        toggleModalOpen('edit');
        setCurrentTableRecord(eventInfo?.tableRecord as TableRecord);
        break;
      }
      case 'add': {
        // 新增必须配置一个详情的ID
        toggleModalOpen('add');
        setCurrentTableRecord({ record: { id: 1 } } as TableRecord);
        break;
      }
      case 'delete': {
        const apiType: ApiType = 'delete';
        const apiInfo: ApiInfo = config.dataSource.apiList[apiType];
        apiInfo.parameter = { id: eventInfo.tableRecord?.record.id };
        dataSource(apiType, apiInfo, '删除成功');
        break;
      }
    }
  };

  [config, setConfig] = useState<any>(initConfig(onSubEvent));

  const getModalNode = (modalType: ModalType) => {
    switch (modalType) {
      case 'setting':
        return <ProFormDynamicSettings config={config} isTable={true} currentTableRecord={currentTableRecord} />;
      case 'add':
        return <ProFormDynamic formType="add" config={config} isTable={true} currentTableRecord={currentTableRecord} />;
      case 'detail':
        return <ProFormDynamic formType="detail" config={config} isTable={true} currentTableRecord={currentTableRecord} />;
      case 'edit':
        return <ProFormDynamic formType="edit" config={config} isTable={true} currentTableRecord={currentTableRecord} />;
    }
  };

  // 菜单中tabs控制的当前表格
  const [proTableMenuInfo, setProTableMenuInfo] = useState<ProTableMenuInfo>({
    activeKey: '',
    menus: [
      { key: '', title: '全部', count: 99 },
      { key: 'normal', title: '正常', count: 29 },
      { key: 'drop', title: '退学', count: 70 },
    ],
  });
  const setActiveMenu = (key: string) => {
    setProTableMenuInfo({ ...proTableMenuInfo, activeKey: key });
    // 全部 / 正常 / 退学
    // setMenuTableState(key);
    proTableActionRef.current?.reload();
  };
  // 处理表格筛选条件
  const parseTableParams = (params: any): ProTableSearch => {
    const dataFromat = 'YYYY-MM-DD HH:mm:ss';
    const search: ProTableSearch = {};

    const { current, pageSize } = params;
    // @ts-ignore
    search[config.dataSource.paginationInfo.currentField] = current;
    // @ts-ignore
    search[config.dataSource.paginationInfo.pageSizeField] = pageSize;

    search.state = proTableMenuInfo.activeKey;

    if (params.createDate && params.createDate.length === 2) {
      search.createStartTime = dayjs(params.createDate[0]).format(dataFromat);
      search.createEndTime = dayjs(params.createDate[1]).format(dataFromat);
    }

    return search;
  };

  return (
    <>
      <ProTable
        formRef={proTableFormRef}
        actionRef={proTableActionRef}
        {...config.tableConfig}
        scroll={config.openScroll ? config.tableConfig.scroll : null}
        footer={config.showFooter ? () => config.tableConfig.footer : undefined}
        options={config.showOptions ? config.tableConfig.options : false}
        pagination={
          config.showPagination
            ? {
                ...config.tableConfig.pagination,
                onChange(page, pageSize) {
                  const newConfig = { ...config };

                  setConfig(newConfig);
                },
              }
            : false
        }
        search={config.showSearch ? { ...config.tableConfig.search } : config.showSearch}
        // ----------分割线-------------
        expandable={config.showExpandable && { expandedRowRender: (record: any) => <>{JSON.stringify(record)}</> }}
        request={async (params, sort, filter) => {
          const apiType: ApiType = 'list';
          const apiInfo: ApiInfo = config.dataSource.apiList[apiType];
          // // 处理表格筛选条件
          apiInfo.body = parseTableParams({
            ...params,
            ...proTableFormRef.current?.getFieldsValue(),
          });

          const dataSourceData: TablePagination = await dataSource(apiType, apiInfo, '');
          if (!dataSourceData) return;
          let proTableData = {
            data: dataSourceData.dataList,
            success: true,
            page: params.current,
            total: dataSourceData.total,
          };
          return proTableData;
        }}
        toolbar={
          config.showToolbar
            ? {
                filter: (
                  <LightFilter>
                    <ProFormDatePicker name="startdate" label="响应日期" />
                  </LightFilter>
                ),
                menu: {
                  type: 'tab',
                  activeKey: proTableMenuInfo.activeKey,
                  items: proTableMenuInfo.menus.map((item, index) => {
                    return {
                      key: item.key,
                      label: (
                        <span>
                          {item.title}（{item.count}）
                        </span>
                      ),
                    };
                  }),
                  onChange: (key: string) => {
                    setActiveMenu(key as string);
                  },
                },
              }
            : false
        }
        toolBarRender={
          config.showToolBarRender
            ? (action) => [
                <Button
                  key="button"
                  icon={<PlusOutlined />}
                  type="primary"
                  onClick={() => onSubEvent({ type: 'add', tableRecord: { reactNode: undefined, index: 0, record: { id: 1 } } })}
                >
                  新建
                </Button>,
              ]
            : false
        }
        // debounceTime={20} // 防抖时间 毫秒
      />

      {modalsInfoConfig
        ? Object.keys(modalsInfoConfig.modals).map((modelType: string, index: number) => {
            const modalInfo: ModalInfo = modalsInfoConfig.modals[modelType as ModalType];
            return (
              <Modal
                title={modalInfo.title}
                open={modalInfo.open}
                key={index}
                onOk={() => toggleModalOpen(modelType as ModalType)}
                onCancel={() => toggleModalOpen(modelType as ModalType)}
                style={{ top: 20 }}
                width={modalInfo.width}
                footer={false}
              >
                <div style={{ overflow: 'auto' }}>
                  {getModalNode(modelType as ModalType)}
                  {/* <ProFormDynamicSettings config={config} isTable={true} currentTableRecord={currentTableRecord} />, */}
                  {/* {modalInfo.reactNode} */}
                </div>
              </Modal>
            );
          })
        : null}
    </>
  );
};

export default ProTableDynamic;
